{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "0",
   "metadata": {},
   "source": [
    "**Interactive mapping and analysis of geospatial big data using geemap and Google Earth Engine**\n",
    "\n",
    "This notebook was developed for the geemap workshop at the [GeoPython 2021 Conference](https://2021.geopython.net).\n",
    "\n",
    "Authors: [Qiusheng Wu](https://github.com/giswqs), [Kel Markert](https://github.com/KMarkert)\n",
    "\n",
    "Link to this notebook: https://gishub.org/geopython\n",
    "\n",
    "Recorded video: https://www.youtube.com/watch?v=wGjpjh9IQ5I\n",
    "\n",
    "[![geemap workship](https://img.youtube.com/vi/wGjpjh9IQ5I/0.jpg)](https://www.youtube.com/watch?v=wGjpjh9IQ5I)\n",
    "\n",
    "\n",
    "## Introduction\n",
    "\n",
    "### Description\n",
    "\n",
    "Google Earth Engine (GEE) is a cloud computing platform with a multi-petabyte catalog of satellite imagery and geospatial datasets. It enables scientists, researchers, and developers to analyze and visualize changes on the Earth’s surface. The geemap Python package provides GEE users with an intuitive interface to manipulate, analyze, and visualize geospatial big data interactively in a Jupyter-based environment. The topics to be covered in this workshop include: \n",
    "\n",
    "1. Introducing geemap and the Earth Engine Python API\n",
    "2. Creating interactive maps\n",
    "3. Searching GEE data catalog\n",
    "4. Displaying GEE datasets\n",
    "5. Classifying images using machine learning algorithms\n",
    "6. Computing statistics and exporting results \n",
    "7. Producing publication-quality maps\n",
    "8. Building and deploying interactive web apps, among others\n",
    "\n",
    "This workshop is intended for scientific programmers, data scientists, geospatial analysts, and concerned citizens of Earth. The attendees are expected to have a basic understanding of Python and the Jupyter ecosystem. Familiarity with Earth science and geospatial datasets is useful but not required.\n",
    "\n",
    "### Useful links\n",
    "- [GeoPython 2021 Conference website](https://2021.geopython.net)\n",
    "- [Google Earth Engine](https://earthengine.google.com)\n",
    "- [geemap.org](https://geemap.org)\n",
    "- [Google Earth Engine and geemap Python Tutorials](https://www.youtube.com/playlist?list=PLAxJ4-o7ZoPccOFv1dCwvGI6TYnirRTg3) (55 videos with a total length of 15 hours)\n",
    "- [Spatial Data Management with Google Earth Engine](https://www.youtube.com/playlist?list=PLAxJ4-o7ZoPdz9LHIJIxHlZe3t-MRCn61) (19 videos with a total length of 9 hours)\n",
    "- [Ask geemap questions on GitHub](https://github.com/gee-community/geemap/discussions)\n",
    "\n",
    "### Prerequisite\n",
    "- A Google Earth Engine account. Sign up [here](https://earthengine.google.com) if needed. \n",
    "- [Miniconda](https://docs.anaconda.com/free/miniconda) or [Anaconda](https://www.anaconda.com/products/individual)\n",
    "\n",
    "\n",
    "### Set up a conda environment\n",
    "\n",
    "```\n",
    "conda create -n geo python=3.8\n",
    "conda activate geo\n",
    "conda install geemap -c conda-forge\n",
    "conda install jupyter_contrib_nbextensions -c conda-forge\n",
    "jupyter contrib nbextension install --user\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1",
   "metadata": {},
   "source": [
    "## geemap basics\n",
    "\n",
    "### Import libraries"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import ee\n",
    "import geemap"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3",
   "metadata": {},
   "source": [
    "### Create an interactive map"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4",
   "metadata": {},
   "outputs": [],
   "source": [
    "Map = geemap.Map()\n",
    "Map"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5",
   "metadata": {},
   "source": [
    "### Customize the default map\n",
    "\n",
    "You can specify the center(lat, lon) and zoom for the default map. The lite mode will only show the zoom in/out tool."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6",
   "metadata": {},
   "outputs": [],
   "source": [
    "Map = geemap.Map(center=(40, -100), zoom=4, lite_mode=True)\n",
    "Map"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7",
   "metadata": {},
   "source": [
    "### Add basemaps"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8",
   "metadata": {},
   "outputs": [],
   "source": [
    "Map = geemap.Map()\n",
    "Map.add_basemap(\"HYBRID\")\n",
    "Map"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9",
   "metadata": {},
   "outputs": [],
   "source": [
    "Map.add_basemap(\"OpenTopoMap\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "10",
   "metadata": {},
   "outputs": [],
   "source": [
    "for basemap in geemap.basemaps.keys():\n",
    "    print(basemap)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "11",
   "metadata": {},
   "source": [
    "### Change basemaps without coding"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "12",
   "metadata": {},
   "source": [
    "![](https://i.imgur.com/PXURCSP.png)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "13",
   "metadata": {},
   "outputs": [],
   "source": [
    "Map = geemap.Map()\n",
    "Map"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "14",
   "metadata": {},
   "source": [
    "### Add WMS and XYZ tile layers\n",
    "\n",
    "Examples: https://viewer.nationalmap.gov/services/"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "15",
   "metadata": {},
   "outputs": [],
   "source": [
    "Map = geemap.Map()\n",
    "\n",
    "url = \"https://mt1.google.com/vt/lyrs=p&x={x}&y={y}&z={z}\"\n",
    "Map.add_tile_layer(url, name=\"Google Terrain\", attribution=\"Google\")\n",
    "Map"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "16",
   "metadata": {},
   "outputs": [],
   "source": [
    "naip_url = \"https://services.nationalmap.gov/arcgis/services/USGSNAIPImagery/ImageServer/WMSServer?\"\n",
    "Map.add_wms_layer(\n",
    "    url=naip_url, layers=\"0\", name=\"NAIP Imagery\", format=\"image/png\", shown=True\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "17",
   "metadata": {},
   "source": [
    "### Use drawing tools"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "18",
   "metadata": {},
   "outputs": [],
   "source": [
    "Map = geemap.Map()\n",
    "Map"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "19",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Map.user_roi.getInfo()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "20",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Map.user_rois.getInfo()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "21",
   "metadata": {},
   "source": [
    "### Convert GEE JavaScript to Python\n",
    "\n",
    "https://developers.google.com/earth-engine/guides/image_visualization"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "22",
   "metadata": {},
   "outputs": [],
   "source": [
    "js_snippet = \"\"\"\n",
    "// Load an image.\n",
    "var image = ee.Image('LANDSAT/LC08/C01/T1_TOA/LC08_044034_20140318');\n",
    "\n",
    "// Define the visualization parameters.\n",
    "var vizParams = {\n",
    "  bands: ['B5', 'B4', 'B3'],\n",
    "  min: 0,\n",
    "  max: 0.5,\n",
    "  gamma: [0.95, 1.1, 1]\n",
    "};\n",
    "\n",
    "// Center the map and display the image.\n",
    "Map.setCenter(-122.1899, 37.5010, 10); // San Francisco Bay\n",
    "Map.addLayer(image, vizParams, 'false color composite');\n",
    "\n",
    "\"\"\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "23",
   "metadata": {},
   "outputs": [],
   "source": [
    "geemap.js_snippet_to_py(\n",
    "    js_snippet, add_new_cell=True, import_ee=True, import_geemap=True, show_map=True\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "24",
   "metadata": {},
   "source": [
    "You can also convert GEE JavaScript to Python without coding.\n",
    "\n",
    "![](https://i.imgur.com/VnnrJwe.png)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "25",
   "metadata": {},
   "outputs": [],
   "source": [
    "Map = geemap.Map()\n",
    "Map"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "26",
   "metadata": {},
   "source": [
    "## Earth Engine datasets\n",
    "\n",
    "### Load Earth Engine datasets"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "27",
   "metadata": {},
   "outputs": [],
   "source": [
    "Map = geemap.Map()\n",
    "\n",
    "# Add Earth Engine datasets\n",
    "dem = ee.Image(\"USGS/SRTMGL1_003\")\n",
    "landcover = ee.Image(\"ESA/GLOBCOVER_L4_200901_200912_V2_3\").select(\"landcover\")\n",
    "landsat7 = ee.Image(\"LANDSAT/LE7_TOA_5YEAR/1999_2003\")\n",
    "states = ee.FeatureCollection(\"TIGER/2018/States\")\n",
    "\n",
    "# Set visualization parameters.\n",
    "vis_params = {\n",
    "    \"min\": 0,\n",
    "    \"max\": 4000,\n",
    "    \"palette\": [\"006633\", \"E5FFCC\", \"662A00\", \"D8D8D8\", \"F5F5F5\"],\n",
    "}\n",
    "\n",
    "# Add Earth Engine layers to Map\n",
    "Map.addLayer(dem, vis_params, \"SRTM DEM\", True, 0.5)\n",
    "Map.addLayer(landcover, {}, \"Land cover\")\n",
    "Map.addLayer(\n",
    "    landsat7,\n",
    "    {\"bands\": [\"B4\", \"B3\", \"B2\"], \"min\": 20, \"max\": 200, \"gamma\": 1.5},\n",
    "    \"Landsat 7\",\n",
    ")\n",
    "Map.addLayer(states, {}, \"US States\")\n",
    "\n",
    "Map"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "28",
   "metadata": {},
   "source": [
    "### Search the Earth Engine Data Catalog"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "29",
   "metadata": {},
   "outputs": [],
   "source": [
    "Map = geemap.Map()\n",
    "Map"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "30",
   "metadata": {},
   "outputs": [],
   "source": [
    "dem = ee.Image(\"CGIAR/SRTM90_V4\")\n",
    "Map.addLayer(dem, {}, \"CGIAR/SRTM90_V4\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "31",
   "metadata": {},
   "outputs": [],
   "source": [
    "vis_params = {\n",
    "    \"min\": 0,\n",
    "    \"max\": 4000,\n",
    "    \"palette\": [\"006633\", \"E5FFCC\", \"662A00\", \"D8D8D8\", \"F5F5F5\"],\n",
    "}\n",
    "\n",
    "Map.addLayer(dem, vis_params, \"DEM\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "32",
   "metadata": {},
   "source": [
    "### Use the datasets module"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "33",
   "metadata": {},
   "outputs": [],
   "source": [
    "from geemap.datasets import DATA"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "34",
   "metadata": {},
   "outputs": [],
   "source": [
    "Map = geemap.Map()\n",
    "\n",
    "dem = ee.Image(DATA.USGS_SRTMGL1_003)\n",
    "\n",
    "vis_params = {\n",
    "    \"min\": 0,\n",
    "    \"max\": 4000,\n",
    "    \"palette\": [\"006633\", \"E5FFCC\", \"662A00\", \"D8D8D8\", \"F5F5F5\"],\n",
    "}\n",
    "\n",
    "Map.addLayer(dem, vis_params, \"SRTM DEM\")\n",
    "Map"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "35",
   "metadata": {},
   "source": [
    "### Use the Inspector tool"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "36",
   "metadata": {},
   "source": [
    "![](https://i.imgur.com/drnfJ6N.png)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "37",
   "metadata": {},
   "outputs": [],
   "source": [
    "Map = geemap.Map()\n",
    "\n",
    "# Add Earth Engine datasets\n",
    "dem = ee.Image(\"USGS/SRTMGL1_003\")\n",
    "landcover = ee.Image(\"ESA/GLOBCOVER_L4_200901_200912_V2_3\").select(\"landcover\")\n",
    "landsat7 = ee.Image(\"LANDSAT/LE7_TOA_5YEAR/1999_2003\").select(\n",
    "    [\"B1\", \"B2\", \"B3\", \"B4\", \"B5\", \"B7\"]\n",
    ")\n",
    "states = ee.FeatureCollection(\"TIGER/2018/States\")\n",
    "\n",
    "# Set visualization parameters.\n",
    "vis_params = {\n",
    "    \"min\": 0,\n",
    "    \"max\": 4000,\n",
    "    \"palette\": [\"006633\", \"E5FFCC\", \"662A00\", \"D8D8D8\", \"F5F5F5\"],\n",
    "}\n",
    "\n",
    "# Add Earth Engine layers to Map\n",
    "Map.addLayer(dem, vis_params, \"SRTM DEM\", True, 0.5)\n",
    "Map.addLayer(landcover, {}, \"Land cover\")\n",
    "Map.addLayer(\n",
    "    landsat7,\n",
    "    {\"bands\": [\"B4\", \"B3\", \"B2\"], \"min\": 20, \"max\": 200, \"gamma\": 1.5},\n",
    "    \"Landsat 7\",\n",
    ")\n",
    "Map.addLayer(states, {}, \"US States\")\n",
    "\n",
    "Map"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "38",
   "metadata": {},
   "source": [
    "## Data visualization \n",
    "\n",
    "### Use the Plotting tool"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "39",
   "metadata": {},
   "source": [
    "![](https://i.imgur.com/t4jKsNo.png)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "40",
   "metadata": {},
   "outputs": [],
   "source": [
    "Map = geemap.Map()\n",
    "\n",
    "landsat7 = ee.Image(\"LANDSAT/LE7_TOA_5YEAR/1999_2003\").select(\n",
    "    [\"B1\", \"B2\", \"B3\", \"B4\", \"B5\", \"B7\"]\n",
    ")\n",
    "\n",
    "landsat_vis = {\"bands\": [\"B4\", \"B3\", \"B2\"], \"gamma\": 1.4}\n",
    "Map.addLayer(landsat7, landsat_vis, \"Landsat\")\n",
    "\n",
    "hyperion = ee.ImageCollection(\"EO1/HYPERION\").filter(\n",
    "    ee.Filter.date(\"2016-01-01\", \"2017-03-01\")\n",
    ")\n",
    "\n",
    "hyperion_vis = {\n",
    "    \"min\": 1000.0,\n",
    "    \"max\": 14000.0,\n",
    "    \"gamma\": 2.5,\n",
    "}\n",
    "Map.addLayer(hyperion, hyperion_vis, \"Hyperion\")\n",
    "\n",
    "Map"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "41",
   "metadata": {},
   "source": [
    "### Change layer opacity"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "42",
   "metadata": {},
   "outputs": [],
   "source": [
    "Map = geemap.Map(center=(40, -100), zoom=4)\n",
    "\n",
    "dem = ee.Image(\"USGS/SRTMGL1_003\")\n",
    "states = ee.FeatureCollection(\"TIGER/2018/States\")\n",
    "\n",
    "vis_params = {\n",
    "    \"min\": 0,\n",
    "    \"max\": 4000,\n",
    "    \"palette\": [\"006633\", \"E5FFCC\", \"662A00\", \"D8D8D8\", \"F5F5F5\"],\n",
    "}\n",
    "\n",
    "Map.addLayer(dem, vis_params, \"SRTM DEM\", True, 1)\n",
    "Map.addLayer(states, {}, \"US States\", True)\n",
    "\n",
    "Map"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "43",
   "metadata": {},
   "source": [
    "### Visualize raster data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "44",
   "metadata": {},
   "outputs": [],
   "source": [
    "Map = geemap.Map(center=(40, -100), zoom=4)\n",
    "\n",
    "# Add Earth Engine dataset\n",
    "dem = ee.Image(\"USGS/SRTMGL1_003\")\n",
    "landsat7 = ee.Image(\"LANDSAT/LE7_TOA_5YEAR/1999_2003\").select(\n",
    "    [\"B1\", \"B2\", \"B3\", \"B4\", \"B5\", \"B7\"]\n",
    ")\n",
    "\n",
    "vis_params = {\n",
    "    \"min\": 0,\n",
    "    \"max\": 4000,\n",
    "    \"palette\": [\"006633\", \"E5FFCC\", \"662A00\", \"D8D8D8\", \"F5F5F5\"],\n",
    "}\n",
    "\n",
    "Map.addLayer(dem, vis_params, \"SRTM DEM\", True, 1)\n",
    "Map.addLayer(\n",
    "    landsat7,\n",
    "    {\"bands\": [\"B4\", \"B3\", \"B2\"], \"min\": 20, \"max\": 200, \"gamma\": 2},\n",
    "    \"Landsat 7\",\n",
    ")\n",
    "Map"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "45",
   "metadata": {},
   "source": [
    "### Visualize vector data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "46",
   "metadata": {},
   "outputs": [],
   "source": [
    "Map = geemap.Map()\n",
    "\n",
    "states = ee.FeatureCollection(\"TIGER/2018/States\")\n",
    "Map.addLayer(states, {}, \"US States\")\n",
    "Map"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "47",
   "metadata": {},
   "outputs": [],
   "source": [
    "vis_params = {\n",
    "    \"color\": \"000000\",\n",
    "    \"colorOpacity\": 1,\n",
    "    \"pointSize\": 3,\n",
    "    \"pointShape\": \"circle\",\n",
    "    \"width\": 2,\n",
    "    \"lineType\": \"solid\",\n",
    "    \"fillColorOpacity\": 0.66,\n",
    "}\n",
    "\n",
    "palette = [\"006633\", \"E5FFCC\", \"662A00\", \"D8D8D8\", \"F5F5F5\"]\n",
    "\n",
    "Map.add_styled_vector(\n",
    "    states, column=\"NAME\", palette=palette, layer_name=\"Styled vector\", **vis_params\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "48",
   "metadata": {},
   "source": [
    "### Add a legend"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "49",
   "metadata": {},
   "outputs": [],
   "source": [
    "legends = geemap.builtin_legends\n",
    "for legend in legends:\n",
    "    print(legend)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "50",
   "metadata": {},
   "outputs": [],
   "source": [
    "Map = geemap.Map()\n",
    "Map.add_basemap(\"HYBRID\")\n",
    "landcover = ee.Image(\"USGS/NLCD/NLCD2016\").select(\"landcover\")\n",
    "Map.addLayer(landcover, {}, \"NLCD Land Cover\")\n",
    "Map.add_legend(builtin_legend=\"NLCD\")\n",
    "Map"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "51",
   "metadata": {},
   "outputs": [],
   "source": [
    "Map = geemap.Map()\n",
    "\n",
    "legend_dict = {\n",
    "    \"11 Open Water\": \"466b9f\",\n",
    "    \"12 Perennial Ice/Snow\": \"d1def8\",\n",
    "    \"21 Developed, Open Space\": \"dec5c5\",\n",
    "    \"22 Developed, Low Intensity\": \"d99282\",\n",
    "    \"23 Developed, Medium Intensity\": \"eb0000\",\n",
    "    \"24 Developed High Intensity\": \"ab0000\",\n",
    "    \"31 Barren Land (Rock/Sand/Clay)\": \"b3ac9f\",\n",
    "    \"41 Deciduous Forest\": \"68ab5f\",\n",
    "    \"42 Evergreen Forest\": \"1c5f2c\",\n",
    "    \"43 Mixed Forest\": \"b5c58f\",\n",
    "    \"51 Dwarf Scrub\": \"af963c\",\n",
    "    \"52 Shrub/Scrub\": \"ccb879\",\n",
    "    \"71 Grassland/Herbaceous\": \"dfdfc2\",\n",
    "    \"72 Sedge/Herbaceous\": \"d1d182\",\n",
    "    \"73 Lichens\": \"a3cc51\",\n",
    "    \"74 Moss\": \"82ba9e\",\n",
    "    \"81 Pasture/Hay\": \"dcd939\",\n",
    "    \"82 Cultivated Crops\": \"ab6c28\",\n",
    "    \"90 Woody Wetlands\": \"b8d9eb\",\n",
    "    \"95 Emergent Herbaceous Wetlands\": \"6c9fb8\",\n",
    "}\n",
    "\n",
    "landcover = ee.Image(\"USGS/NLCD/NLCD2016\").select(\"landcover\")\n",
    "Map.addLayer(landcover, {}, \"NLCD Land Cover\")\n",
    "\n",
    "Map.add_legend(legend_title=\"NLCD Land Cover Classification\", legend_dict=legend_dict)\n",
    "Map"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "52",
   "metadata": {},
   "source": [
    "### Add a colorbar"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "53",
   "metadata": {},
   "outputs": [],
   "source": [
    "Map = geemap.Map()\n",
    "\n",
    "dem = ee.Image(\"USGS/SRTMGL1_003\")\n",
    "vis_params = {\n",
    "    \"min\": 0,\n",
    "    \"max\": 4000,\n",
    "    \"palette\": [\"006633\", \"E5FFCC\", \"662A00\", \"D8D8D8\", \"F5F5F5\"],\n",
    "}\n",
    "\n",
    "Map.addLayer(dem, vis_params, \"SRTM DEM\")\n",
    "\n",
    "colors = vis_params[\"palette\"]\n",
    "vmin = vis_params[\"min\"]\n",
    "vmax = vis_params[\"max\"]\n",
    "\n",
    "Map.add_colorbar(vis_params, label=\"Elevation (m)\", layer_name=\"SRTM DEM\")\n",
    "Map"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "54",
   "metadata": {},
   "outputs": [],
   "source": [
    "Map.add_colorbar(\n",
    "    vis_params, label=\"Elevation (m)\", layer_name=\"SRTM DEM\", orientation=\"vertical\"\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "55",
   "metadata": {},
   "outputs": [],
   "source": [
    "Map.add_colorbar(\n",
    "    vis_params,\n",
    "    label=\"Elevation (m)\",\n",
    "    layer_name=\"SRTM DEM\",\n",
    "    orientation=\"vertical\",\n",
    "    transparent_bg=True,\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "56",
   "metadata": {},
   "outputs": [],
   "source": [
    "Map.add_colorbar(\n",
    "    vis_params,\n",
    "    label=\"Elevation (m)\",\n",
    "    layer_name=\"SRTM DEM\",\n",
    "    orientation=\"vertical\",\n",
    "    transparent_bg=True,\n",
    "    discrete=True,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "57",
   "metadata": {},
   "source": [
    "### Create a split-panel map"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "58",
   "metadata": {},
   "outputs": [],
   "source": [
    "Map = geemap.Map()\n",
    "Map.split_map(left_layer=\"HYBRID\", right_layer=\"TERRAIN\")\n",
    "Map"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "59",
   "metadata": {},
   "outputs": [],
   "source": [
    "Map = geemap.Map()\n",
    "Map.split_map(\n",
    "    left_layer=\"NLCD 2016 CONUS Land Cover\", right_layer=\"NLCD 2001 CONUS Land Cover\"\n",
    ")\n",
    "Map"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "60",
   "metadata": {},
   "outputs": [],
   "source": [
    "nlcd_2001 = ee.Image(\"USGS/NLCD/NLCD2001\").select(\"landcover\")\n",
    "nlcd_2016 = ee.Image(\"USGS/NLCD/NLCD2016\").select(\"landcover\")\n",
    "\n",
    "left_layer = geemap.ee_tile_layer(nlcd_2001, {}, \"NLCD 2001\")\n",
    "right_layer = geemap.ee_tile_layer(nlcd_2016, {}, \"NLCD 2016\")\n",
    "\n",
    "Map = geemap.Map()\n",
    "Map.split_map(left_layer, right_layer)\n",
    "Map"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "61",
   "metadata": {},
   "source": [
    "### Create linked maps"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "62",
   "metadata": {},
   "outputs": [],
   "source": [
    "image = (\n",
    "    ee.ImageCollection(\"COPERNICUS/S2\")\n",
    "    .filterDate(\"2018-09-01\", \"2018-09-30\")\n",
    "    .map(lambda img: img.divide(10000))\n",
    "    .median()\n",
    ")\n",
    "\n",
    "vis_params = [\n",
    "    {\"bands\": [\"B4\", \"B3\", \"B2\"], \"min\": 0, \"max\": 0.3, \"gamma\": 1.3},\n",
    "    {\"bands\": [\"B8\", \"B11\", \"B4\"], \"min\": 0, \"max\": 0.3, \"gamma\": 1.3},\n",
    "    {\"bands\": [\"B8\", \"B4\", \"B3\"], \"min\": 0, \"max\": 0.3, \"gamma\": 1.3},\n",
    "    {\"bands\": [\"B12\", \"B12\", \"B4\"], \"min\": 0, \"max\": 0.3, \"gamma\": 1.3},\n",
    "]\n",
    "\n",
    "labels = [\n",
    "    \"Natural Color (B4/B3/B2)\",\n",
    "    \"Land/Water (B8/B11/B4)\",\n",
    "    \"Color Infrared (B8/B4/B3)\",\n",
    "    \"Vegetation (B12/B11/B4)\",\n",
    "]\n",
    "\n",
    "geemap.linked_maps(\n",
    "    rows=2,\n",
    "    cols=2,\n",
    "    height=\"400px\",\n",
    "    center=[38.4151, 21.2712],\n",
    "    zoom=12,\n",
    "    ee_objects=[image],\n",
    "    vis_params=vis_params,\n",
    "    labels=labels,\n",
    "    label_position=\"topright\",\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "63",
   "metadata": {},
   "source": [
    "### Create timelapse animations"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "64",
   "metadata": {},
   "outputs": [],
   "source": [
    "geemap.show_youtube(\"https://youtu.be/mA21Us_3m28\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "65",
   "metadata": {},
   "source": [
    "### Create time-series composites"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "66",
   "metadata": {},
   "outputs": [],
   "source": [
    "geemap.show_youtube(\"https://youtu.be/kEltQkNia6o\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "67",
   "metadata": {},
   "source": [
    "## Data analysis"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "68",
   "metadata": {},
   "source": [
    "### Descriptive statistics"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "69",
   "metadata": {},
   "outputs": [],
   "source": [
    "Map = geemap.Map()\n",
    "\n",
    "centroid = ee.Geometry.Point([-122.4439, 37.7538])\n",
    "\n",
    "image = ee.ImageCollection(\"LANDSAT/LC08/C01/T1_SR\").filterBounds(centroid).first()\n",
    "\n",
    "vis = {\"min\": 0, \"max\": 3000, \"bands\": [\"B5\", \"B4\", \"B3\"]}\n",
    "\n",
    "Map.centerObject(centroid, 8)\n",
    "Map.addLayer(image, vis, \"Landsat-8\")\n",
    "Map"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "70",
   "metadata": {},
   "outputs": [],
   "source": [
    "image.propertyNames().getInfo()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "71",
   "metadata": {},
   "outputs": [],
   "source": [
    "image.get(\"CLOUD_COVER\").getInfo()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "72",
   "metadata": {},
   "outputs": [],
   "source": [
    "props = geemap.image_props(image)\n",
    "props.getInfo()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "73",
   "metadata": {},
   "outputs": [],
   "source": [
    "stats = geemap.image_stats(image, scale=90)\n",
    "stats.getInfo()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "74",
   "metadata": {},
   "source": [
    "### Zonal statistics"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "75",
   "metadata": {},
   "outputs": [],
   "source": [
    "Map = geemap.Map()\n",
    "\n",
    "# Add Earth Engine dataset\n",
    "dem = ee.Image(\"USGS/SRTMGL1_003\")\n",
    "\n",
    "# Set visualization parameters.\n",
    "dem_vis = {\n",
    "    \"min\": 0,\n",
    "    \"max\": 4000,\n",
    "    \"palette\": [\"006633\", \"E5FFCC\", \"662A00\", \"D8D8D8\", \"F5F5F5\"],\n",
    "}\n",
    "\n",
    "# Add Earth Engine DEM to map\n",
    "Map.addLayer(dem, dem_vis, \"SRTM DEM\")\n",
    "\n",
    "# Add Landsat data to map\n",
    "landsat = ee.Image(\"LANDSAT/LE7_TOA_5YEAR/1999_2003\")\n",
    "\n",
    "landsat_vis = {\"bands\": [\"B4\", \"B3\", \"B2\"], \"gamma\": 1.4}\n",
    "Map.addLayer(landsat, landsat_vis, \"LE7_TOA_5YEAR/1999_2003\")\n",
    "\n",
    "states = ee.FeatureCollection(\"TIGER/2018/States\")\n",
    "Map.addLayer(states, {}, \"US States\")\n",
    "Map"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "76",
   "metadata": {},
   "outputs": [],
   "source": [
    "out_dir = os.path.expanduser(\"~/Downloads\")\n",
    "out_dem_stats = os.path.join(out_dir, \"dem_stats.csv\")\n",
    "\n",
    "if not os.path.exists(out_dir):\n",
    "    os.makedirs(out_dir)\n",
    "\n",
    "# Allowed output formats: csv, shp, json, kml, kmz\n",
    "# Allowed statistics type: MEAN, MAXIMUM, MINIMUM, MEDIAN, STD, MIN_MAX, VARIANCE, SUM\n",
    "geemap.zonal_stats(dem, states, out_dem_stats, stat_type=\"MEAN\", scale=1000)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "77",
   "metadata": {},
   "outputs": [],
   "source": [
    "out_landsat_stats = os.path.join(out_dir, \"landsat_stats.csv\")\n",
    "geemap.zonal_stats(landsat, states, out_landsat_stats, stat_type=\"SUM\", scale=1000)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "78",
   "metadata": {},
   "source": [
    "### Zonal statistics by group"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "79",
   "metadata": {},
   "outputs": [],
   "source": [
    "Map = geemap.Map()\n",
    "\n",
    "dataset = ee.Image(\"USGS/NLCD/NLCD2016\")\n",
    "landcover = ee.Image(dataset.select(\"landcover\"))\n",
    "Map.addLayer(landcover, {}, \"NLCD 2016\")\n",
    "\n",
    "states = ee.FeatureCollection(\"TIGER/2018/States\")\n",
    "Map.addLayer(states, {}, \"US States\")\n",
    "Map.add_legend(builtin_legend=\"NLCD\")\n",
    "Map"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "80",
   "metadata": {},
   "outputs": [],
   "source": [
    "out_dir = os.path.expanduser(\"~/Downloads\")\n",
    "nlcd_stats = os.path.join(out_dir, \"nlcd_stats.csv\")\n",
    "\n",
    "if not os.path.exists(out_dir):\n",
    "    os.makedirs(out_dir)\n",
    "\n",
    "# statistics_type can be either 'SUM' or 'PERCENTAGE'\n",
    "# denominator can be used to convert square meters to other areal units, such as square kilimeters\n",
    "geemap.zonal_stats_by_group(\n",
    "    landcover,\n",
    "    states,\n",
    "    nlcd_stats,\n",
    "    stat_type=\"SUM\",\n",
    "    denominator=1000000,\n",
    "    decimal_places=2,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "81",
   "metadata": {},
   "source": [
    "### Unsupervised classification\n",
    "\n",
    "Source: https://developers.google.com/earth-engine/guides/clustering\n",
    "\n",
    "The `ee.Clusterer` package handles unsupervised classification (or clustering) in Earth Engine. These algorithms are currently based on the algorithms with the same name in [Weka](http://www.cs.waikato.ac.nz/ml/weka/). More details about each Clusterer are available in the reference docs in the Code Editor.\n",
    "\n",
    "Clusterers are used in the same manner as classifiers in Earth Engine. The general workflow for clustering is:\n",
    "\n",
    "1. Assemble features with numeric properties in which to find clusters.\n",
    "2. Instantiate a clusterer. Set its parameters if necessary.\n",
    "3. Train the clusterer using the training data.\n",
    "4. Apply the clusterer to an image or feature collection.\n",
    "5. Label the clusters.\n",
    "\n",
    "The training data is a `FeatureCollection` with properties that will be input to the clusterer. Unlike classifiers, there is no input class value for an `Clusterer`. Like classifiers, the data for the train and apply steps are expected to have the same number of values. When a trained clusterer is applied to an image or table, it assigns an integer cluster ID to each pixel or feature.\n",
    "\n",
    "Here is a simple example of building and using an ee.Clusterer:\n",
    "\n",
    "![](https://i.imgur.com/IcBapEx.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "82",
   "metadata": {},
   "source": [
    "**Add data to the map**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "83",
   "metadata": {},
   "outputs": [],
   "source": [
    "Map = geemap.Map()\n",
    "\n",
    "point = ee.Geometry.Point([-87.7719, 41.8799])\n",
    "\n",
    "image = (\n",
    "    ee.ImageCollection(\"LANDSAT/LC08/C01/T1_SR\")\n",
    "    .filterBounds(point)\n",
    "    .filterDate(\"2019-01-01\", \"2019-12-31\")\n",
    "    .sort(\"CLOUD_COVER\")\n",
    "    .first()\n",
    "    .select(\"B[1-7]\")\n",
    ")\n",
    "\n",
    "vis_params = {\"min\": 0, \"max\": 3000, \"bands\": [\"B5\", \"B4\", \"B3\"]}\n",
    "\n",
    "Map.centerObject(point, 8)\n",
    "Map.addLayer(image, vis_params, \"Landsat-8\")\n",
    "\n",
    "Map"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "84",
   "metadata": {},
   "source": [
    "**Make training dataset**\n",
    "\n",
    "There are several ways you can create a region for generating the training dataset.\n",
    "\n",
    "- Draw a shape (e.g., rectangle) on the map and the use `region = Map.user_roi`\n",
    "- Define a geometry, such as `region = ee.Geometry.Rectangle([-122.6003, 37.4831, -121.8036, 37.8288])`\n",
    "- Create a buffer zone around a point, such as `region = ee.Geometry.Point([-122.4439, 37.7538]).buffer(10000)`\n",
    "- If you don't define a region, it will use the image footprint by default"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "85",
   "metadata": {},
   "outputs": [],
   "source": [
    "training = image.sample(\n",
    "    **{\n",
    "        #     'region': region,\n",
    "        \"scale\": 30,\n",
    "        \"numPixels\": 5000,\n",
    "        \"seed\": 0,\n",
    "        \"geometries\": True,  # Set this to False to ignore geometries\n",
    "    }\n",
    ")\n",
    "\n",
    "Map.addLayer(training, {}, \"training\", False)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "86",
   "metadata": {},
   "source": [
    "**Train the clusterer**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "87",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Instantiate the clusterer and train it.\n",
    "n_clusters = 5\n",
    "clusterer = ee.Clusterer.wekaKMeans(n_clusters).train(training)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "88",
   "metadata": {},
   "source": [
    "**Classify the image**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "89",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Cluster the input using the trained clusterer.\n",
    "result = image.cluster(clusterer)\n",
    "\n",
    "# # Display the clusters with random colors.\n",
    "Map.addLayer(result.randomVisualizer(), {}, \"clusters\")\n",
    "Map"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "90",
   "metadata": {},
   "source": [
    "**Label the clusters**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "91",
   "metadata": {},
   "outputs": [],
   "source": [
    "legend_keys = [\"One\", \"Two\", \"Three\", \"Four\", \"etc\"]\n",
    "legend_colors = [\"#8DD3C7\", \"#FFFFB3\", \"#BEBADA\", \"#FB8072\", \"#80B1D3\"]\n",
    "\n",
    "# Reclassify the map\n",
    "result = result.remap([0, 1, 2, 3, 4], [1, 2, 3, 4, 5])\n",
    "\n",
    "Map.addLayer(\n",
    "    result, {\"min\": 1, \"max\": 5, \"palette\": legend_colors}, \"Labelled clusters\"\n",
    ")\n",
    "Map.add_legend(\n",
    "    legend_keys=legend_keys, legend_colors=legend_colors, position=\"bottomright\"\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "92",
   "metadata": {},
   "source": [
    "**Visualize the result**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "93",
   "metadata": {},
   "outputs": [],
   "source": [
    "print(\"Change layer opacity:\")\n",
    "cluster_layer = Map.layers[-1]\n",
    "cluster_layer.interact(opacity=(0, 1, 0.1))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "94",
   "metadata": {},
   "outputs": [],
   "source": [
    "Map"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "95",
   "metadata": {},
   "source": [
    "**Export the result**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "96",
   "metadata": {},
   "outputs": [],
   "source": [
    "out_dir = os.path.expanduser(\"~/Downloads\")\n",
    "out_file = os.path.join(out_dir, \"cluster.tif\")\n",
    "geemap.ee_export_image(result, filename=out_file, scale=90)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "97",
   "metadata": {},
   "outputs": [],
   "source": [
    "# geemap.ee_export_image_to_drive(result, description='clusters', folder='export', scale=90)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "98",
   "metadata": {},
   "source": [
    "### Supervised classification"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "99",
   "metadata": {},
   "source": [
    "Source: https://developers.google.com/earth-engine/guides/classification\n",
    "\n",
    "The `Classifier` package handles supervised classification by traditional ML algorithms running in Earth Engine. These classifiers include CART, RandomForest, NaiveBayes and SVM. The general workflow for classification is:\n",
    "\n",
    "1. Collect training data. Assemble features which have a property that stores the known class label and properties storing numeric values for the predictors.\n",
    "2. Instantiate a classifier. Set its parameters if necessary.\n",
    "3. Train the classifier using the training data.\n",
    "4. Classify an image or feature collection.\n",
    "5. Estimate classification error with independent validation data.\n",
    "\n",
    "The training data is a `FeatureCollection` with a property storing the class label and properties storing predictor variables. Class labels should be consecutive, integers starting from 0. If necessary, use remap() to convert class values to consecutive integers. The predictors should be numeric.\n",
    "\n",
    "![](https://i.imgur.com/vROsEiq.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "100",
   "metadata": {},
   "source": [
    "**Add data to the map**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "101",
   "metadata": {},
   "outputs": [],
   "source": [
    "Map = geemap.Map()\n",
    "\n",
    "point = ee.Geometry.Point([-122.4439, 37.7538])\n",
    "\n",
    "image = (\n",
    "    ee.ImageCollection(\"LANDSAT/LC08/C01/T1_SR\")\n",
    "    .filterBounds(point)\n",
    "    .filterDate(\"2016-01-01\", \"2016-12-31\")\n",
    "    .sort(\"CLOUD_COVER\")\n",
    "    .first()\n",
    "    .select(\"B[1-7]\")\n",
    ")\n",
    "\n",
    "vis_params = {\"min\": 0, \"max\": 3000, \"bands\": [\"B5\", \"B4\", \"B3\"]}\n",
    "\n",
    "Map.centerObject(point, 8)\n",
    "Map.addLayer(image, vis_params, \"Landsat-8\")\n",
    "\n",
    "Map"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "102",
   "metadata": {},
   "source": [
    "**Make training dataset**\n",
    "\n",
    "There are several ways you can create a region for generating the training dataset.\n",
    "\n",
    "- Draw a shape (e.g., rectangle) on the map and the use `region = Map.user_roi`\n",
    "- Define a geometry, such as `region = ee.Geometry.Rectangle([-122.6003, 37.4831, -121.8036, 37.8288])`\n",
    "- Create a buffer zone around a point, such as `region = ee.Geometry.Point([-122.4439, 37.7538]).buffer(10000)`\n",
    "- If you don't define a region, it will use the image footprint by default"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "103",
   "metadata": {},
   "outputs": [],
   "source": [
    "# region = Map.user_roi\n",
    "# region = ee.Geometry.Rectangle([-122.6003, 37.4831, -121.8036, 37.8288])\n",
    "# region = ee.Geometry.Point([-122.4439, 37.7538]).buffer(10000)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "104",
   "metadata": {},
   "source": [
    "In this example, we are going to use the [USGS National Land Cover Database (NLCD)](https://developers.google.com/earth-engine/datasets/catalog/USGS_NLCD) to create label dataset for training\n",
    "\n",
    "\n",
    "![](https://i.imgur.com/7QoRXxu.png)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "105",
   "metadata": {},
   "outputs": [],
   "source": [
    "nlcd = ee.Image(\"USGS/NLCD/NLCD2016\").select(\"landcover\").clip(image.geometry())\n",
    "Map.addLayer(nlcd, {}, \"NLCD\")\n",
    "Map"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "106",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Make the training dataset.\n",
    "points = nlcd.sample(\n",
    "    **{\n",
    "        \"region\": image.geometry(),\n",
    "        \"scale\": 30,\n",
    "        \"numPixels\": 5000,\n",
    "        \"seed\": 0,\n",
    "        \"geometries\": True,  # Set this to False to ignore geometries\n",
    "    }\n",
    ")\n",
    "\n",
    "Map.addLayer(points, {}, \"training\", False)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "107",
   "metadata": {},
   "source": [
    "**Train the classifier**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "108",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Use these bands for prediction.\n",
    "bands = [\"B1\", \"B2\", \"B3\", \"B4\", \"B5\", \"B6\", \"B7\"]\n",
    "\n",
    "\n",
    "# This property of the table stores the land cover labels.\n",
    "label = \"landcover\"\n",
    "\n",
    "# Overlay the points on the imagery to get training.\n",
    "training = image.select(bands).sampleRegions(\n",
    "    **{\"collection\": points, \"properties\": [label], \"scale\": 30}\n",
    ")\n",
    "\n",
    "# Train a CART classifier with default parameters.\n",
    "trained = ee.Classifier.smileCart().train(training, label, bands)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "109",
   "metadata": {},
   "source": [
    "**Classify the image**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "110",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Classify the image with the same bands used for training.\n",
    "result = image.select(bands).classify(trained)\n",
    "\n",
    "# # Display the clusters with random colors.\n",
    "Map.addLayer(result.randomVisualizer(), {}, \"classified\")\n",
    "Map"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "111",
   "metadata": {},
   "source": [
    "**Render categorical map**\n",
    "\n",
    "To render a categorical map, we can set two image properties: `landcover_class_values` and `landcover_class_palette`. We can use the same style as the NLCD so that it is easy to compare the two maps."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "112",
   "metadata": {},
   "outputs": [],
   "source": [
    "class_values = nlcd.get(\"landcover_class_values\").getInfo()\n",
    "class_palette = nlcd.get(\"landcover_class_palette\").getInfo()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "113",
   "metadata": {},
   "outputs": [],
   "source": [
    "landcover = result.set(\"classification_class_values\", class_values)\n",
    "landcover = landcover.set(\"classification_class_palette\", class_palette)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "114",
   "metadata": {},
   "outputs": [],
   "source": [
    "Map.addLayer(landcover, {}, \"Land cover\")\n",
    "Map.add_legend(builtin_legend=\"NLCD\")\n",
    "Map"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "115",
   "metadata": {},
   "source": [
    "**Visualize the result**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "116",
   "metadata": {},
   "outputs": [],
   "source": [
    "print(\"Change layer opacity:\")\n",
    "cluster_layer = Map.layers[-1]\n",
    "cluster_layer.interact(opacity=(0, 1, 0.1))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "117",
   "metadata": {},
   "source": [
    "**Export the result**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "118",
   "metadata": {},
   "outputs": [],
   "source": [
    "out_dir = os.path.expanduser(\"~/Downloads\")\n",
    "out_file = os.path.join(out_dir, \"landcover.tif\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "119",
   "metadata": {},
   "outputs": [],
   "source": [
    "geemap.ee_export_image(landcover, filename=out_file, scale=900)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "120",
   "metadata": {},
   "outputs": [],
   "source": [
    "# geemap.ee_export_image_to_drive(landcover, description='landcover', folder='export', scale=900)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "121",
   "metadata": {},
   "source": [
    "### Training sample creation\n",
    "\n",
    "![](https://i.imgur.com/QQDjcPt.png)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "122",
   "metadata": {},
   "outputs": [],
   "source": [
    "geemap.show_youtube(\"https://youtu.be/VWh5PxXPZw0\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "123",
   "metadata": {},
   "outputs": [],
   "source": [
    "Map = geemap.Map()\n",
    "Map"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "124",
   "metadata": {},
   "source": [
    "### WhiteboxTools"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "125",
   "metadata": {},
   "outputs": [],
   "source": [
    "import whiteboxgui"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "126",
   "metadata": {},
   "outputs": [],
   "source": [
    "whiteboxgui.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "127",
   "metadata": {},
   "outputs": [],
   "source": [
    "whiteboxgui.show(tree=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "128",
   "metadata": {},
   "source": [
    "![](https://i.imgur.com/aNRfUIf.png)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "129",
   "metadata": {},
   "outputs": [],
   "source": [
    "Map = geemap.Map()\n",
    "Map"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "130",
   "metadata": {},
   "source": [
    "## Map making"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "131",
   "metadata": {},
   "source": [
    "### Plot a single band image"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "132",
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "from geemap import cartoee"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "133",
   "metadata": {},
   "outputs": [],
   "source": [
    "geemap.ee_initialize()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "134",
   "metadata": {},
   "outputs": [],
   "source": [
    "srtm = ee.Image(\"CGIAR/SRTM90_V4\")\n",
    "region = [-180, -60, 180, 85]  # define bounding box to request data\n",
    "vis = {\"min\": 0, \"max\": 3000}  # define visualization parameters for image"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "135",
   "metadata": {},
   "outputs": [],
   "source": [
    "fig = plt.figure(figsize=(15, 10))\n",
    "\n",
    "cmap = \"gist_earth\"  # colormap we want to use\n",
    "# cmap = \"terrain\"\n",
    "\n",
    "# use cartoee to get a map\n",
    "ax = cartoee.get_map(srtm, region=region, vis_params=vis, cmap=cmap)\n",
    "\n",
    "# add a colorbar to the map using the visualization params we passed to the map\n",
    "cartoee.add_colorbar(\n",
    "    ax, vis, cmap=cmap, loc=\"right\", label=\"Elevation\", orientation=\"vertical\"\n",
    ")\n",
    "\n",
    "# add gridlines to the map at a specified interval\n",
    "cartoee.add_gridlines(ax, interval=[60, 30], linestyle=\"--\")\n",
    "\n",
    "# add coastlines using the cartopy api\n",
    "ax.coastlines(color=\"red\")\n",
    "\n",
    "ax.set_title(label=\"Global Elevation Map\", fontsize=15)\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "136",
   "metadata": {},
   "source": [
    "### Plot an RGB image"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "137",
   "metadata": {},
   "outputs": [],
   "source": [
    "# get a landsat image to visualize\n",
    "image = ee.Image(\"LANDSAT/LC08/C01/T1_SR/LC08_044034_20140318\")\n",
    "\n",
    "# define the visualization parameters to view\n",
    "vis = {\"bands\": [\"B5\", \"B4\", \"B3\"], \"min\": 0, \"max\": 5000, \"gamma\": 1.3}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "138",
   "metadata": {},
   "outputs": [],
   "source": [
    "fig = plt.figure(figsize=(15, 10))\n",
    "\n",
    "# here is the bounding box of the map extent we want to use\n",
    "# formatted a [W,S,E,N]\n",
    "zoom_region = [-122.6265, 37.3458, -121.8025, 37.9178]\n",
    "\n",
    "# plot the map over the region of interest\n",
    "ax = cartoee.get_map(image, vis_params=vis, region=zoom_region)\n",
    "\n",
    "# add the gridlines and specify that the xtick labels be rotated 45 degrees\n",
    "cartoee.add_gridlines(ax, interval=0.15, xtick_rotation=45, linestyle=\":\")\n",
    "\n",
    "# add coastline\n",
    "ax.coastlines(color=\"yellow\")\n",
    "\n",
    "# add north arrow\n",
    "cartoee.add_north_arrow(\n",
    "    ax, text=\"N\", xy=(0.05, 0.25), text_color=\"white\", arrow_color=\"white\", fontsize=20\n",
    ")\n",
    "\n",
    "# add scale bar\n",
    "cartoee.add_scale_bar_lite(\n",
    "    ax, length=10, xy=(0.1, 0.05), fontsize=20, color=\"white\", unit=\"km\"\n",
    ")\n",
    "\n",
    "ax.set_title(label=\"Landsat False Color Composite (Band 5/4/3)\", fontsize=15)\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "139",
   "metadata": {},
   "source": [
    "### Add map elements"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "140",
   "metadata": {},
   "outputs": [],
   "source": [
    "from matplotlib.lines import Line2D"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "141",
   "metadata": {},
   "outputs": [],
   "source": [
    "# get a landsat image to visualize\n",
    "image = ee.Image(\"LANDSAT/LC08/C01/T1_SR/LC08_044034_20140318\")\n",
    "\n",
    "# define the visualization parameters to view\n",
    "vis = {\"bands\": [\"B5\", \"B4\", \"B3\"], \"min\": 0, \"max\": 5000, \"gamma\": 1.3}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "142",
   "metadata": {},
   "outputs": [],
   "source": [
    "fig = plt.figure(figsize=(15, 10))\n",
    "\n",
    "# here is the bounding box of the map extent we want to use\n",
    "# formatted a [W,S,E,N]\n",
    "zoom_region = [-122.6265, 37.3458, -121.8025, 37.9178]\n",
    "\n",
    "# plot the map over the region of interest\n",
    "ax = cartoee.get_map(image, vis_params=vis, region=zoom_region)\n",
    "\n",
    "# add the gridlines and specify that the xtick labels be rotated 45 degrees\n",
    "cartoee.add_gridlines(ax, interval=0.15, xtick_rotation=0, linestyle=\":\")\n",
    "\n",
    "# add coastline\n",
    "ax.coastlines(color=\"cyan\")\n",
    "\n",
    "# add north arrow\n",
    "cartoee.add_north_arrow(\n",
    "    ax, text=\"N\", xy=(0.05, 0.25), text_color=\"white\", arrow_color=\"white\", fontsize=20\n",
    ")\n",
    "\n",
    "# add scale bar\n",
    "cartoee.add_scale_bar_lite(\n",
    "    ax, length=10, xy=(0.1, 0.05), fontsize=20, color=\"white\", unit=\"km\"\n",
    ")\n",
    "\n",
    "ax.set_title(label=\"Landsat False Color Composite (Band 5/4/3)\", fontsize=15)\n",
    "\n",
    "# add legend\n",
    "legend_elements = [\n",
    "    Line2D([], [], color=\"#00ffff\", lw=2, label=\"Coastline\"),\n",
    "    Line2D(\n",
    "        [],\n",
    "        [],\n",
    "        marker=\"o\",\n",
    "        color=\"#A8321D\",\n",
    "        label=\"City\",\n",
    "        markerfacecolor=\"#A8321D\",\n",
    "        markersize=10,\n",
    "        ls=\"\",\n",
    "    ),\n",
    "]\n",
    "\n",
    "cartoee.add_legend(ax, legend_elements, loc=\"lower right\")\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "143",
   "metadata": {},
   "source": [
    "### Plot multiple layers"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "144",
   "metadata": {},
   "outputs": [],
   "source": [
    "Map = geemap.Map()\n",
    "\n",
    "image = (\n",
    "    ee.ImageCollection(\"MODIS/MCD43A4_006_NDVI\")\n",
    "    .filter(ee.Filter.date(\"2018-04-01\", \"2018-05-01\"))\n",
    "    .select(\"NDVI\")\n",
    "    .first()\n",
    ")\n",
    "\n",
    "vis_params = {\n",
    "    \"min\": 0.0,\n",
    "    \"max\": 1.0,\n",
    "    \"palette\": [\n",
    "        \"FFFFFF\",\n",
    "        \"CE7E45\",\n",
    "        \"DF923D\",\n",
    "        \"F1B555\",\n",
    "        \"FCD163\",\n",
    "        \"99B718\",\n",
    "        \"74A901\",\n",
    "        \"66A000\",\n",
    "        \"529400\",\n",
    "        \"3E8601\",\n",
    "        \"207401\",\n",
    "        \"056201\",\n",
    "        \"004C00\",\n",
    "        \"023B01\",\n",
    "        \"012E01\",\n",
    "        \"011D01\",\n",
    "        \"011301\",\n",
    "    ],\n",
    "}\n",
    "Map.setCenter(-7.03125, 31.0529339857, 2)\n",
    "Map.addLayer(image, vis_params, \"MODIS NDVI\")\n",
    "\n",
    "countries = geemap.shp_to_ee(\"../data/countries.shp\")\n",
    "style = {\"color\": \"00000088\", \"width\": 1, \"fillColor\": \"00000000\"}\n",
    "Map.addLayer(countries.style(**style), {}, \"Countries\")\n",
    "\n",
    "ndvi = image.visualize(**vis_params)\n",
    "blend = ndvi.blend(countries.style(**style))\n",
    "\n",
    "Map.addLayer(blend, {}, \"Blend\")\n",
    "\n",
    "Map"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "145",
   "metadata": {},
   "outputs": [],
   "source": [
    "# specify region to focus on\n",
    "bbox = [-180, -88, 180, 88]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "146",
   "metadata": {},
   "outputs": [],
   "source": [
    "fig = plt.figure(figsize=(15, 10))\n",
    "\n",
    "# plot the result with cartoee using a PlateCarre projection (default)\n",
    "ax = cartoee.get_map(blend, region=bbox)\n",
    "cb = cartoee.add_colorbar(ax, vis_params=vis_params, loc=\"right\")\n",
    "\n",
    "ax.set_title(label=\"MODIS NDVI\", fontsize=15)\n",
    "\n",
    "# ax.coastlines()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "147",
   "metadata": {},
   "outputs": [],
   "source": [
    "import cartopy.crs as ccrs"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "148",
   "metadata": {},
   "outputs": [],
   "source": [
    "fig = plt.figure(figsize=(15, 10))\n",
    "\n",
    "projection = ccrs.EqualEarth(central_longitude=-180)\n",
    "\n",
    "# plot the result with cartoee using a PlateCarre projection (default)\n",
    "ax = cartoee.get_map(blend, region=bbox, proj=projection)\n",
    "cb = cartoee.add_colorbar(ax, vis_params=vis_params, loc=\"right\")\n",
    "\n",
    "ax.set_title(label=\"MODIS NDVI\", fontsize=15)\n",
    "\n",
    "# ax.coastlines()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "149",
   "metadata": {},
   "source": [
    "### Use custom projections"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "150",
   "metadata": {},
   "outputs": [],
   "source": [
    "import cartopy.crs as ccrs"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "151",
   "metadata": {},
   "outputs": [],
   "source": [
    "# get an earth engine image of ocean data for Jan-Mar 2018\n",
    "ocean = (\n",
    "    ee.ImageCollection(\"NASA/OCEANDATA/MODIS-Terra/L3SMI\")\n",
    "    .filter(ee.Filter.date(\"2018-01-01\", \"2018-03-01\"))\n",
    "    .median()\n",
    "    .select([\"sst\"], [\"SST\"])\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "152",
   "metadata": {},
   "outputs": [],
   "source": [
    "# set parameters for plotting\n",
    "# will plot the Sea Surface Temp with specific range and colormap\n",
    "visualization = {\"bands\": \"SST\", \"min\": -2, \"max\": 30}\n",
    "# specify region to focus on\n",
    "bbox = [-180, -88, 180, 88]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "153",
   "metadata": {},
   "outputs": [],
   "source": [
    "fig = plt.figure(figsize=(15, 10))\n",
    "\n",
    "# plot the result with cartoee using a PlateCarre projection (default)\n",
    "ax = cartoee.get_map(ocean, cmap=\"plasma\", vis_params=visualization, region=bbox)\n",
    "cb = cartoee.add_colorbar(ax, vis_params=visualization, loc=\"right\", cmap=\"plasma\")\n",
    "\n",
    "ax.set_title(label=\"Sea Surface Temperature\", fontsize=15)\n",
    "\n",
    "ax.coastlines()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "154",
   "metadata": {},
   "outputs": [],
   "source": [
    "fig = plt.figure(figsize=(15, 10))\n",
    "\n",
    "# create a new Mollweide projection centered on the Pacific\n",
    "projection = ccrs.Mollweide(central_longitude=-180)\n",
    "\n",
    "# plot the result with cartoee using the Mollweide projection\n",
    "ax = cartoee.get_map(\n",
    "    ocean, vis_params=visualization, region=bbox, cmap=\"plasma\", proj=projection\n",
    ")\n",
    "cb = cartoee.add_colorbar(\n",
    "    ax, vis_params=visualization, loc=\"bottom\", cmap=\"plasma\", orientation=\"horizontal\"\n",
    ")\n",
    "\n",
    "ax.set_title(\"Mollweide projection\")\n",
    "\n",
    "ax.coastlines()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "155",
   "metadata": {},
   "outputs": [],
   "source": [
    "fig = plt.figure(figsize=(15, 10))\n",
    "\n",
    "# create a new Robinson projection centered on the Pacific\n",
    "projection = ccrs.Robinson(central_longitude=-180)\n",
    "\n",
    "# plot the result with cartoee using the Goode homolosine projection\n",
    "ax = cartoee.get_map(\n",
    "    ocean, vis_params=visualization, region=bbox, cmap=\"plasma\", proj=projection\n",
    ")\n",
    "cb = cartoee.add_colorbar(\n",
    "    ax, vis_params=visualization, loc=\"bottom\", cmap=\"plasma\", orientation=\"horizontal\"\n",
    ")\n",
    "\n",
    "ax.set_title(\"Robinson projection\")\n",
    "\n",
    "ax.coastlines()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "156",
   "metadata": {},
   "outputs": [],
   "source": [
    "fig = plt.figure(figsize=(15, 10))\n",
    "\n",
    "# create a new equal Earth projection focused on the Pacific\n",
    "projection = ccrs.EqualEarth(central_longitude=-180)\n",
    "\n",
    "# plot the result with cartoee using the orographic projection\n",
    "ax = cartoee.get_map(\n",
    "    ocean, vis_params=visualization, region=bbox, cmap=\"plasma\", proj=projection\n",
    ")\n",
    "cb = cartoee.add_colorbar(\n",
    "    ax, vis_params=visualization, loc=\"right\", cmap=\"plasma\", orientation=\"vertical\"\n",
    ")\n",
    "\n",
    "ax.set_title(\"Equal Earth projection\")\n",
    "\n",
    "ax.coastlines()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "157",
   "metadata": {},
   "outputs": [],
   "source": [
    "fig = plt.figure(figsize=(15, 10))\n",
    "\n",
    "# create a new orographic projection focused on the Pacific\n",
    "projection = ccrs.Orthographic(-130, -10)\n",
    "\n",
    "# plot the result with cartoee using the orographic projection\n",
    "ax = cartoee.get_map(\n",
    "    ocean, vis_params=visualization, region=bbox, cmap=\"plasma\", proj=projection\n",
    ")\n",
    "cb = cartoee.add_colorbar(\n",
    "    ax, vis_params=visualization, loc=\"right\", cmap=\"plasma\", orientation=\"vertical\"\n",
    ")\n",
    "\n",
    "ax.set_title(\"Orographic projection\")\n",
    "\n",
    "ax.coastlines()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "158",
   "metadata": {},
   "source": [
    "### Create timelapse animations"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "159",
   "metadata": {},
   "outputs": [],
   "source": [
    "Map = geemap.Map()\n",
    "\n",
    "lon = -115.1585\n",
    "lat = 36.1500\n",
    "start_year = 1984\n",
    "end_year = 2000\n",
    "\n",
    "point = ee.Geometry.Point(lon, lat)\n",
    "years = ee.List.sequence(start_year, end_year)\n",
    "\n",
    "\n",
    "def get_best_image(year):\n",
    "    start_date = ee.Date.fromYMD(year, 1, 1)\n",
    "    end_date = ee.Date.fromYMD(year, 12, 31)\n",
    "    image = (\n",
    "        ee.ImageCollection(\"LANDSAT/LT05/C01/T1_SR\")\n",
    "        .filterBounds(point)\n",
    "        .filterDate(start_date, end_date)\n",
    "        .sort(\"CLOUD_COVER\")\n",
    "        .first()\n",
    "    )\n",
    "    return ee.Image(image)\n",
    "\n",
    "\n",
    "collection = ee.ImageCollection(years.map(get_best_image))\n",
    "\n",
    "vis_params = {\"bands\": [\"B4\", \"B3\", \"B2\"], \"min\": 0, \"max\": 5000}\n",
    "\n",
    "image = ee.Image(collection.first())\n",
    "Map.addLayer(image, vis_params, \"First image\")\n",
    "Map.setCenter(lon, lat, 8)\n",
    "Map"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "160",
   "metadata": {},
   "outputs": [],
   "source": [
    "w = 0.4\n",
    "h = 0.3\n",
    "\n",
    "region = [lon - w, lat - h, lon + w, lat + h]\n",
    "\n",
    "fig = plt.figure(figsize=(10, 8))\n",
    "\n",
    "# use cartoee to get a map\n",
    "ax = cartoee.get_map(image, region=region, vis_params=vis_params)\n",
    "\n",
    "# add gridlines to the map at a specified interval\n",
    "cartoee.add_gridlines(ax, interval=[0.2, 0.2], linestyle=\":\")\n",
    "\n",
    "# add north arrow\n",
    "north_arrow_dict = {\n",
    "    \"text\": \"N\",\n",
    "    \"xy\": (0.1, 0.3),\n",
    "    \"arrow_length\": 0.15,\n",
    "    \"text_color\": \"white\",\n",
    "    \"arrow_color\": \"white\",\n",
    "    \"fontsize\": 20,\n",
    "    \"width\": 5,\n",
    "    \"headwidth\": 15,\n",
    "    \"ha\": \"center\",\n",
    "    \"va\": \"center\",\n",
    "}\n",
    "cartoee.add_north_arrow(ax, **north_arrow_dict)\n",
    "\n",
    "# add scale bar\n",
    "scale_bar_dict = {\n",
    "    \"length\": 10,\n",
    "    \"xy\": (0.1, 0.05),\n",
    "    \"linewidth\": 3,\n",
    "    \"fontsize\": 20,\n",
    "    \"color\": \"white\",\n",
    "    \"unit\": \"km\",\n",
    "    \"ha\": \"center\",\n",
    "    \"va\": \"bottom\",\n",
    "}\n",
    "cartoee.add_scale_bar_lite(ax, **scale_bar_dict)\n",
    "\n",
    "ax.set_title(label=\"Las Vegas, NV\", fontsize=15)\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "161",
   "metadata": {},
   "outputs": [],
   "source": [
    "cartoee.get_image_collection_gif(\n",
    "    ee_ic=collection,\n",
    "    out_dir=os.path.expanduser(\"~/Downloads/timelapse\"),\n",
    "    out_gif=\"animation.gif\",\n",
    "    vis_params=vis_params,\n",
    "    region=region,\n",
    "    fps=5,\n",
    "    mp4=True,\n",
    "    grid_interval=(0.2, 0.2),\n",
    "    plot_title=\"Las Vegas, NV\",\n",
    "    date_format=\"YYYY-MM-dd\",\n",
    "    fig_size=(10, 8),\n",
    "    dpi_plot=100,\n",
    "    file_format=\"png\",\n",
    "    north_arrow_dict=north_arrow_dict,\n",
    "    scale_bar_dict=scale_bar_dict,\n",
    "    verbose=True,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "162",
   "metadata": {},
   "source": [
    "## Data export"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "163",
   "metadata": {},
   "source": [
    "### Export ee.Image"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "164",
   "metadata": {},
   "outputs": [],
   "source": [
    "Map = geemap.Map()\n",
    "\n",
    "image = ee.Image(\"LANDSAT/LE7_TOA_5YEAR/1999_2003\")\n",
    "\n",
    "landsat_vis = {\"bands\": [\"B4\", \"B3\", \"B2\"], \"gamma\": 1.4}\n",
    "Map.addLayer(image, landsat_vis, \"LE7_TOA_5YEAR/1999_2003\", True, 1)\n",
    "\n",
    "Map"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "165",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Draw any shapes on the map using the Drawing tools before executing this code block\n",
    "roi = Map.user_roi\n",
    "\n",
    "if roi is None:\n",
    "    roi = ee.Geometry.Polygon(\n",
    "        [\n",
    "            [\n",
    "                [-115.413031, 35.889467],\n",
    "                [-115.413031, 36.543157],\n",
    "                [-114.034328, 36.543157],\n",
    "                [-114.034328, 35.889467],\n",
    "                [-115.413031, 35.889467],\n",
    "            ]\n",
    "        ]\n",
    "    )"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "166",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Set output directory\n",
    "out_dir = os.path.expanduser(\"~/Downloads\")\n",
    "\n",
    "if not os.path.exists(out_dir):\n",
    "    os.makedirs(out_dir)\n",
    "\n",
    "filename = os.path.join(out_dir, \"landsat.tif\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "167",
   "metadata": {},
   "source": [
    "Exporting all bands as one single image"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "168",
   "metadata": {},
   "outputs": [],
   "source": [
    "image = image.clip(roi).unmask()\n",
    "geemap.ee_export_image(\n",
    "    image, filename=filename, scale=90, region=roi, file_per_band=False\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "169",
   "metadata": {},
   "source": [
    "Exporting each band as one image"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "170",
   "metadata": {},
   "outputs": [],
   "source": [
    "geemap.ee_export_image(\n",
    "    image, filename=filename, scale=90, region=roi, file_per_band=True\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "171",
   "metadata": {},
   "source": [
    "Export an image to Google Drive¶"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "172",
   "metadata": {},
   "outputs": [],
   "source": [
    "# geemap.ee_export_image_to_drive(image, description='landsat', folder='export', region=roi, scale=30)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "173",
   "metadata": {},
   "source": [
    "### Export ee.ImageCollection"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "174",
   "metadata": {},
   "outputs": [],
   "source": [
    "loc = ee.Geometry.Point(-99.2222, 46.7816)\n",
    "collection = (\n",
    "    ee.ImageCollection(\"USDA/NAIP/DOQQ\")\n",
    "    .filterBounds(loc)\n",
    "    .filterDate(\"2008-01-01\", \"2020-01-01\")\n",
    "    .filter(ee.Filter.listContains(\"system:band_names\", \"N\"))\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "175",
   "metadata": {},
   "outputs": [],
   "source": [
    "collection.aggregate_array(\"system:index\").getInfo()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "176",
   "metadata": {},
   "outputs": [],
   "source": [
    "geemap.ee_export_image_collection(collection, out_dir=out_dir)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "177",
   "metadata": {},
   "outputs": [],
   "source": [
    "# geemap.ee_export_image_collection_to_drive(collection, folder='export', scale=10)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "178",
   "metadata": {},
   "source": [
    "### Extract pixels as a numpy array"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "179",
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "\n",
    "img = ee.Image(\"LANDSAT/LC08/C01/T1_SR/LC08_038029_20180810\").select([\"B4\", \"B5\", \"B6\"])\n",
    "\n",
    "aoi = ee.Geometry.Polygon(\n",
    "    [[[-110.8, 44.7], [-110.8, 44.6], [-110.6, 44.6], [-110.6, 44.7]]], None, False\n",
    ")\n",
    "\n",
    "rgb_img = geemap.ee_to_numpy(img, region=aoi)\n",
    "print(rgb_img.shape)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "180",
   "metadata": {},
   "outputs": [],
   "source": [
    "rgb_img_test = (255 * ((rgb_img[:, :, 0:3] - 100) / 3500)).astype(\"uint8\")\n",
    "plt.imshow(rgb_img_test)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "181",
   "metadata": {},
   "source": [
    "### Export pixel values to points"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "182",
   "metadata": {},
   "outputs": [],
   "source": [
    "Map = geemap.Map()\n",
    "\n",
    "# Add Earth Engine dataset\n",
    "dem = ee.Image(\"USGS/SRTMGL1_003\")\n",
    "landsat7 = ee.Image(\"LANDSAT/LE7_TOA_5YEAR/1999_2003\")\n",
    "\n",
    "# Set visualization parameters.\n",
    "vis_params = {\n",
    "    \"min\": 0,\n",
    "    \"max\": 4000,\n",
    "    \"palette\": [\"006633\", \"E5FFCC\", \"662A00\", \"D8D8D8\", \"F5F5F5\"],\n",
    "}\n",
    "\n",
    "# Add Earth Engine layers to Map\n",
    "Map.addLayer(\n",
    "    landsat7, {\"bands\": [\"B4\", \"B3\", \"B2\"], \"min\": 20, \"max\": 200}, \"Landsat 7\"\n",
    ")\n",
    "Map.addLayer(dem, vis_params, \"SRTM DEM\", True, 1)\n",
    "Map"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "183",
   "metadata": {},
   "source": [
    "**Download sample data**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "184",
   "metadata": {},
   "outputs": [],
   "source": [
    "work_dir = os.path.expanduser(\"~/Downloads\")\n",
    "in_shp = os.path.join(work_dir, \"us_cities.shp\")\n",
    "if not os.path.exists(in_shp):\n",
    "    data_url = \"https://github.com/giswqs/data/raw/main/us/us_cities.zip\"\n",
    "    geemap.download_from_url(data_url, out_dir=work_dir)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "185",
   "metadata": {},
   "outputs": [],
   "source": [
    "in_fc = geemap.shp_to_ee(in_shp)\n",
    "Map.addLayer(in_fc, {}, \"Cities\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "186",
   "metadata": {},
   "source": [
    "**Export pixel values as a shapefile**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "187",
   "metadata": {},
   "outputs": [],
   "source": [
    "out_shp = os.path.join(work_dir, \"dem.shp\")\n",
    "geemap.extract_values_to_points(in_fc, dem, out_shp)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "188",
   "metadata": {},
   "source": [
    "**Export pixel values as a csv**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "189",
   "metadata": {},
   "outputs": [],
   "source": [
    "out_csv = os.path.join(work_dir, \"landsat.csv\")\n",
    "geemap.extract_values_to_points(in_fc, landsat7, out_csv)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "190",
   "metadata": {},
   "source": [
    "### Export ee.FeatureCollection"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "191",
   "metadata": {},
   "outputs": [],
   "source": [
    "Map = geemap.Map()\n",
    "\n",
    "fc = ee.FeatureCollection(\"users/giswqs/public/countries\")\n",
    "Map.addLayer(fc, {}, \"Countries\")\n",
    "Map"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "192",
   "metadata": {},
   "outputs": [],
   "source": [
    "out_dir = os.path.expanduser(\"~/Downloads\")\n",
    "out_shp = os.path.join(out_dir, \"countries.shp\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "193",
   "metadata": {},
   "outputs": [],
   "source": [
    "geemap.ee_to_shp(fc, filename=out_shp)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "194",
   "metadata": {},
   "outputs": [],
   "source": [
    "out_csv = os.path.join(out_dir, \"countries.csv\")\n",
    "geemap.ee_export_vector(fc, filename=out_csv)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "195",
   "metadata": {},
   "outputs": [],
   "source": [
    "out_kml = os.path.join(out_dir, \"countries.kml\")\n",
    "geemap.ee_export_vector(fc, filename=out_kml)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "196",
   "metadata": {},
   "outputs": [],
   "source": [
    "# geemap.ee_export_vector_to_drive(fc, description=\"countries\", folder=\"export\", file_format=\"shp\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "197",
   "metadata": {},
   "source": [
    "## Web apps"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "198",
   "metadata": {},
   "source": [
    "### Deploy web apps using ngrok"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "199",
   "metadata": {},
   "source": [
    "**Steps to deploy an Earth Engine App:**\n",
    "1. Install ngrok by following the [instruction](https://ngrok.com/download)\n",
    "3. Download the notebook [71_timelapse.ipynb](https://geemap.org/notebooks/71_timelapse/71_timelapse.ipynb) \n",
    "4. Run this from the command line: `voila --no-browser 71_timelapse.ipynb`\n",
    "5. Run this from the command line: `ngrok http 8866`\n",
    "6. Copy the link from the ngrok terminal window. The links looks like the following: https://randomstring.ngrok.io\n",
    "7. Share the link with anyone. \n",
    "\n",
    "**Optional steps:**\n",
    "* To show code cells from you app, run this from the command line: `voila --no-browser --strip_sources=False 71_timelapse.ipynb`\n",
    "* To protect your app with a password, run this: `ngrok http -auth=\"username:password\" 8866`\n",
    "* To run python simple http server in the directory, run this:`sudo python -m http.server 80`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "200",
   "metadata": {},
   "outputs": [],
   "source": [
    "geemap.show_youtube(\"https://youtu.be/eRDZBVJcNCk\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "201",
   "metadata": {},
   "source": [
    "### Deploy web apps using Heroku"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "202",
   "metadata": {},
   "source": [
    "**Steps to deploy an Earth Engine App:**\n",
    "\n",
    "- [Sign up](https://signup.heroku.com/) for a free heroku account.\n",
    "- Follow the [instructions](https://devcenter.heroku.com/articles/getting-started-with-python#set-up) to install [Git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) and Heroku Command Line Interface (CLI).\n",
    "- Authenticate heroku using the `heroku login` command.\n",
    "- Clone this repository: <https://github.com/gee-community/geemap-heroku>\n",
    "- Create your own Earth Engine notebook and put it under the `notebooks` directory.\n",
    "- Add Python dependencies in the `requirements.txt` file if needed.\n",
    "- Edit the `Procfile` file by replacing `notebooks/geemap.ipynb` with the path to your own notebook.\n",
    "- Commit changes to the repository by using `git add . && git commit -am \"message\"`.\n",
    "- Create a heroku app: `heroku create`\n",
    "- Run the `config_vars.py` script to extract Earth Engine token from your computer and set it as an environment variable on heroku: `python config_vars.py`\n",
    "- Deploy your code to heroku: `git push heroku master`\n",
    "- Open your heroku app: `heroku open`\n",
    "\n",
    "**Optional steps:**\n",
    "\n",
    "- To specify a name for your app, use `heroku apps:create example`\n",
    "- To preview your app locally, use `heroku local web`\n",
    "- To hide code cells from your app, you can edit the `Procfile` file and set `--strip_sources=True`\n",
    "- To periodically check for idle kernels, you can edit the `Procfile` file and set `--MappingKernelManager.cull_interval=60 --MappingKernelManager.cull_idle_timeout=120`\n",
    "- To view information about your running app, use `heroku logs --tail`\n",
    "- To set an environment variable on heroku, use `heroku config:set NAME=VALUE`\n",
    "- To view environment variables for your app, use `heroku config`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "203",
   "metadata": {},
   "outputs": [],
   "source": [
    "geemap.show_youtube(\"https://youtu.be/nsIjfD83ggA\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
